<template>
  <div>
    <el-card>
      <el-button
        type="primary"
        icon="Plus"
        style="margin-bottom: 15px"
        @click="addTradeMark"
      >
        添加品牌
      </el-button>
      <!-- 表格 -->
      <el-table
        :data="trademarkArr"
        border
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column label="序号" width="180" type="index" />
        <el-table-column prop="tmName" label="品牌名称" width="180" />
        <!-- table-column：默认用div展示数据。可以用插槽自定义 -->
        <el-table-column label="品牌LOGO">
          <template #default="{ row }">
            <img
              :src="row.logoUrl"
              alt="图片丢啦~"
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #default="{ row }">
            <el-button
              type="primary"
              icon="Edit"
              size="small"
              @click="upDataTradeMark(row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              title="你确定删除?"
              icon="Delete"
              icon-color="red"
              @confirm="deleteTradeMark(row.id)"
              confirm-button-type="text"
              cancel-button-type="primary"
            >
              <template #reference>
                <el-button type="danger" icon="Delete" size="small">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="demo-pagination-block" style="margin-top: 15px">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[3, 5, 7, 9]"
          :background="true"
          layout=" prev, pager, next, jumper, -> ,sizes,total"
          :total="total"
          @change="getHasTradeMark"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>
    <!-- 对话框 -->
    <!-- v-model属性；控制对话框的显示和隐藏 -->
    <el-dialog v-model="dialogFormVisible" :title="title">
      <el-form
        ref="form"
        label-width="100px"
        style="width: 80%; padding: 20px"
        :rules="rules"
        :model="trademarkParams"
        validate=""
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            placeholder="请您输入品牌名称"
            v-model="trademarkParams.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- action:上传图片的请求地址 -->
          <!-- show-file-list:是否展示上传图片的列表 -->
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 具名插槽 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqHasTradeMark,
  reqAddTradeMark,
  reqUpdateTradeMark,
  reqDeleteTradeMark,
} from '../../../api/product/trademark'
import type { Records } from '../../../api/product/trademark/type'
import type {
  TrademarkResponseData,
  Trademark,
} from '../../../api/product/trademark/type'

//控制对话框显示隐藏
const dialogFormVisible = ref<boolean>(false)

//当前页码
const currentPage = ref<number>(1)
//每页显示条数
const pageSize = ref<number>(3)
//存储已有品牌数据总数
let total = ref<number>(0)
//表格数据
let trademarkArr = ref<Records>([])
//收集新增品牌数据
let trademarkParams = reactive<Trademark>({
  tmName: '',
  logoUrl: '',
  id: null,
})
//对话框标题
let title = ref<string>('')

//获取el-form组件实例
let form = ref()

//上传图片成功回调函数:收集图片地址数据
//response:上传图片成功后，服务器返回的数据
//uploadFile:上传图片成功后，服务器返回的图片信息
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  console.log('上传图片成功后,服务器返回的数据和图片信息', response, uploadFile)
  //收集图片地址数据
  trademarkParams.logoUrl = 'http://localhost:8081' + response.data
  form.value.clearValidate('logoUrl')
}

//上传图片之前回调函数:约束上传图片的格式和大小
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage.error('请上传小于4MB的图片')
      return false
    }
  } else {
    ElMessage.error('请上传jpg、png、gif格式的图片')
    return false
  }
}

//点击添加品牌按钮逻辑
const addTradeMark = () => {
  title.value = '添加品牌'
  //清空数据
  trademarkParams.id = null
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
  dialogFormVisible.value = true

  //重置该表单项:首次执行需要挂载form元素，所以需要用nextTick.用?也可以
  nextTick(() => {
    //不传字段名可以实现全部清除
    form.value.clearValidate()
  })
}

//修改品牌逻辑
const upDataTradeMark = (row: Trademark) => {
  //清除掉校验规则
  nextTick(() => {
    form.value.clearValidate()
  })
  title.value = '修改品牌'
  //展示数据
  //ES6语法：合并对象
  //不能使用展开运算符，因为row是响应式数据，展开运算符会将其变为普通对象
  Object.assign(trademarkParams, row)
  dialogFormVisible.value = true
}

//点击对话框的确定按钮
const handleConfirm = async () => {
  //在发请求之前，对整个表单进行校验
  //await失败(校验不通过)，会返回失败的promise，不会执行后面的语句
  await form.value.validate()
  let result: TrademarkResponseData
  if (trademarkParams.id) {
    //修改品牌
    result = await reqUpdateTradeMark(trademarkParams)
  } else {
    //添加品牌
    result = await reqAddTradeMark(trademarkParams)
  }

  if (result.code == 200) {
    //关闭对话框
    dialogFormVisible.value = false
    //弹出提示消息
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
    })
    //重新获取品牌列表数据
    //停留在当前页码trademarkParams.id?pageNo.value:1
    getHasTradeMark()
    //使当前页面跳转到最后一页
  } else {
    dialogFormVisible.value = false
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败',
    })
  }
}

//将获取品牌列表数据接口封装为一个函数：在任何情况下获取数据，调用此函数即可
const getHasTradeMark = async () => {
  let result: TrademarkResponseData = await reqHasTradeMark(
    currentPage.value,
    pageSize.value,
  )
  // console.log("品牌请求数据", result)
  if (result.code == 200) {
    total.value = result.data.total
    trademarkArr.value = result.data.records
  }
}
//组件挂载完毕，发一次请求，获取第一页、一页4条数据
onMounted(() => {
  getHasTradeMark()
})

const handleSizeChange = () => {
  //当前每一页数据量发生变化时，当前页码归一
  currentPage.value = 1
}

//校验品牌名称
const validateTmName = (rule: any, value: any, callback: any) => {
  if (value.length < 2 || value.length > 10) {
    callback(new Error('品牌名称长度在2到10个字符之间'))
  } else {
    callback()
  }
}
//校验品牌logo
const validateLogoUrl = (rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('请上传品牌图片'))
  }
}
//表单校验
const rules = {
  // requiered: true意为必填项
  tmName: [{ required: true, validator: validateTmName, trigger: 'blur' }],
  // 对于图片，Trigger不起作用.图片不属于文本框、文本域。
  logoUrl: [{ required: true, validator: validateLogoUrl }],
}

//删除品牌
const deleteTradeMark = async (id: number) => {
  let result = await reqDeleteTradeMark(id)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    })
    //重新获取品牌列表数据
    getHasTradeMark()
    //停留在当前页码trademarkParams.id?pageNo.value:1
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败',
    })
  }
}
defineOptions({
  name: 'Trademark',
})
</script>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
